import Vue from 'vue';

let {throttle} = require('lodash/fp')
/***
 *  节流 指令
 *  注意:
 *    如果 leading 和 trailing 都设定为 true 则 func 允许 trailing 方式调用的条件为: 在 wait 期间多次调用。
 *    如果 wait 为 0 并且 leading 为 false, func调用将被推迟到下一个点，类似setTimeout为0的超时。
 *  例：<el-button v-throttle="[()=>reset(param),`click`,500,{leading:true,trailing:true}]">刷新</el-button>
 *  @see lodash.throttle https://www.lodashjs.com/docs/lodash.throttle
 */
Vue.directive('throttle', {
  inserted: function (el, binding) {
    let defaultOption={leading:true,trailing:true}
    //数组解构
    let [func, event = "click", wait = 500,option=defaultOption] = binding.value
    el.addEventListener(event,()=>{
      throttle(func,wait,option)
    })
    /*let timer, timer_end;
    el.addEventListener(event, () => {
      if (timer) {
        clearTimeout(timer_end);
        return timer_end = setTimeout(() => func(), time);
      }
      func();
      timer = setTimeout(() => timer = null, time)
    })*/
  }
})
